package com.service;

import com.database.DatabaseConnection;
import com.model.Class;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class ClassService {
    private DatabaseConnection dbConnection;

    public ClassService(DatabaseConnection dbConnection) {
        this.dbConnection = dbConnection;
    }

    public void addClass(String className) {
        String sql = "INSERT INTO Classes (name) VALUES (?)";
        try (Connection connection = dbConnection.getConnection();
             PreparedStatement statement = connection.prepareStatement(sql)) {
            statement.setString(1, className);
            statement.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    public void updateClass(int classId, String newClassName) {
        String sql = "UPDATE Classes SET name = ? WHERE id = ?";
        try (Connection connection = dbConnection.getConnection();
             PreparedStatement statement = connection.prepareStatement(sql)) {
            statement.setString(1, newClassName);
            statement.setInt(2, classId);
            statement.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    public List<Class> getClassListByName(String namePattern) {
        List<Class> classes = new ArrayList<>();
        String sql = "SELECT * FROM Classes WHERE name LIKE ?";
        try (Connection connection = dbConnection.getConnection();
             PreparedStatement statement = connection.prepareStatement(sql)) {
            statement.setString(1, "%" + namePattern + "%");
            ResultSet resultSet = statement.executeQuery();
            while (resultSet.next()) {
                int id = resultSet.getInt("id");
                String name = resultSet.getString("name");
                classes.add(new Class(id, name));
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return classes;
    }

    public List<Class> getClassList() {
        List<Class> classes = new ArrayList<>();
        String sql = "SELECT * FROM Classes";
        try (Connection connection = dbConnection.getConnection();
             PreparedStatement statement = connection.prepareStatement(sql);
             ResultSet resultSet = statement.executeQuery()) {
            while (resultSet.next()) {
                int id = resultSet.getInt("id");
                String name = resultSet.getString("name");
                classes.add(new Class(id, name));
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return classes;
    }

    public void deleteClass(int classId) {
    }
}